package org.budo.support.lang.util;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author limingwei2
 */
public class SystemUtil {
    private static final Logger log = LoggerFactory.getLogger(SystemUtil.class);

    public static Properties getProperties() {
        Properties properties = new Properties();
        properties.putAll(System.getProperties());
        return properties;
    }

    public static void setProperty(String key, String value) {
        System.setProperty(key, value);
    }

    public static String getProperty(String key, String defaultValue) {
        Properties properties = getProperties();
        if (null == properties || null == key) {
            log.warn("#23 getProperty return null, properties=" + properties + ", key=" + key);
            return null;
        }

        return properties.getProperty(key, defaultValue);
    }

    public static Properties getEnv() {
        Properties properties = new Properties();
        properties.putAll(System.getenv());
        return properties;
    }

    public static Properties getEnvAndProperties() {
        Properties properties = new Properties();
        properties.putAll(System.getenv());
        properties.putAll(System.getProperties());
        return properties;
    }

    public static String getEnvOrProperty(String key) {
        return getEnvAndProperties().getProperty(key);
    }

    public static String getEnvOrProperty(String key, String defaultValue) {
        Properties envAndProperties = getEnvAndProperties();
        return envAndProperties.getProperty(key, defaultValue);
    }

    public static String getJavaVersion() {
        return getEnvOrProperty("java.version", "not specified");
    }

    public static String getJavaHome() {
        return getEnvOrProperty("java.home", "not specified");
    }

    public static String getOsName() {
        return getEnvOrProperty("os.name", "not specified");
    }

    public static Boolean isWindows() {
        String osName = getOsName();
        return StringUtil.containsIgnoreCase(osName, "win");
    }

    public static Integer getInteger(String key) {
        String value = getEnvOrProperty(key);

        if (StringUtil.isEmpty(value)) {
            return null;
        }

        return NumberUtil.toInteger(value);
    }
}